/*
 * @Author: ZhanXie
 * @Date: 2020-05-11 09:11:21
 * @LastEditors: ZhanXie
 * @LastEditTime: 2020-07-01 09:27:16
 * @Description: 
 * @FilePath: /projectStudy/mini-redux/src/mini-react-redux.js
 */ 
import React from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from './mini-redux'

/* 
connect 负责链接组件，把redux里面的state和包装后的action放到组件的属性里
1.负责接收一个组件，吧state里的数据放进去
2.数据变化的时候，能够通知组件
*/

// function aConnect(mapStateToProps = state => state, mapStateToProps = {}) {
//   return function(WrapComponent) {
//     return class ConnectComponent extends React.Component {
      
//     }
//   }
// }

export const connect = (mapStateToProps=state=>state,mapDisPatchToProps={}) => (WrapComponent) => {
  return class ConnectComponent extends React.Component{
    static contextTypes = {
      store: PropTypes.object
    }
    constructor(props,context) {
      super(props,context)
      this.state={props:{}}
    }
    componentDidMount() {
      const { store } = this.context
      store.subscribe(()=>this.update())
      this.update()
    }
    update() {
      const { store } = this.context
      const stateProps = mapStateToProps(store.getState())
      const dispatchProps = bindActionCreators(mapDisPatchToProps,store.dispatch)
      this.setState({
        props:{
          ...this.props,
          ...stateProps,
          ...dispatchProps
        }
      })
    }
    render() {
      return <WrapComponent {...this.state.props} />
    }
  }
}

/* Provider吧store放到context里，所有的子元素都可以直接获取store */
export class Provider extends React.Component{
  static childContextTypes = {
    store: PropTypes.object
  }
  getChildContext() {
    return {
      store:this.store
    }
  }
  constructor (props,context) {
    super(props,context)
    this.store = props.store
  }

  render() {
    return this.props.children
  }
}